package com.qf.commons.event.core.handle;

import com.qf.commons.event.core.standrad.ProduceInterceptor;
import com.qf.commons.event.core.standrad.ProduceStandrad;
import com.qf.commons.event.entity.QphoneMessage;
import com.qf.commons.event.mq.standrad.MqProduceStandard;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * description:
 * author: Ken
 * 公众号：Java架构栈
 */
@Component
public class DefaultProduceStandrad implements ProduceStandrad {

    @Autowired(required = false)
    private List<ProduceInterceptor> produceInterceptors;

    @Autowired
    private MqProduceStandard mqProduceStandard;

    @Override
    public void sendMessage(QphoneMessage qphoneMessage) {
        //对当前消息进行一些预处理
        if (CollectionUtils.isEmpty(produceInterceptors)) {
            //直接调用底层接口，将msg发送出去
            mqProduceStandard.sendMessage(qphoneMessage);
            return;
        }

        //拦截器链存在
        QphoneMessage temMessage = qphoneMessage;
        //循环拦截器，依次处理
        for (ProduceInterceptor produceInterceptor : produceInterceptors) {
            try {
                //判断当前的消息是否符合拦截器的要求
                if (!produceInterceptor.isSupport(temMessage)) continue;
                //使用当前拦截器处理该消息
                temMessage = produceInterceptor.sendPreProcessor(temMessage);
                //判断消息是否为空，如果为空表示消息不再发送
                if (temMessage == null) return;
            } catch (Exception e) {
                //日志记录异常...
            }
        }

        //直接调用底层接口，将msg发送出去
        mqProduceStandard.sendMessage(temMessage);
    }
}
